package com.cqut.ktpspring.service.impl;

import com.cqut.ktpspring.exception.ServiceException;
import com.cqut.ktpspring.mapper.AnswerMapper;
import com.cqut.ktpspring.mapper.CourseMapper;
import com.cqut.ktpspring.mapper.CourseMemberMapper;
import com.cqut.ktpspring.mapper.WorkMapper;
import com.cqut.ktpspring.pojo.Course;
import com.cqut.ktpspring.pojo.CourseMember;
import com.cqut.ktpspring.pojo.User;
import com.cqut.ktpspring.pojo.Work;
import com.cqut.ktpspring.service.CourseMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CourseMemberServiceimpl implements CourseMemberService {
    @Autowired
    private CourseMemberMapper courseMemberMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private WorkMapper workMapper;
    @Autowired
    private AnswerMapper answerMapper;
    @Override
    @Transactional
    public void addMember(String cno, String userId) {
        Course course=courseMapper.selectById(cno);
        if(course==null||course.getDeleted()==1){
            throw new ServiceException("课程不存在或已被删除");
        }
        CourseMember courseMember=courseMemberMapper.getCourseMember(cno, userId);
        if(courseMember!=null) {
            if (courseMember.getStatus()==1){
                throw new ServiceException("学生已存在");
            }
            else {
                courseMember.setStatus(0);
                courseMemberMapper.updateById(courseMember);
                courseMemberMapper.updateMember(cno);
            }
        }else {
            courseMemberMapper.add(cno, userId);
            courseMemberMapper.updateMember(cno);
        }
        //学生成功加入课程，把相关的作业信息也存好
        List<Work> works=workMapper.selectWorks(cno);
        for(Work work:works){
            answerMapper.addAnswer(userId,work.getId());
        }
    }


    @Override
    public void deleteMembers(String cno, List<String> members) {
        for(String member:members){
            CourseMember courseMember=courseMemberMapper.getCourseMember(cno, member);
            courseMember.setStatus(2);
            System.out.println(courseMember);
            courseMemberMapper.updateById(courseMember);
            courseMemberMapper.minusMember(cno);
        }
        System.out.println("退课成功");
    }


    @Override
    public List<String> getCourseMembers(String cno) {
        return courseMemberMapper.getCourseMembers(cno);
    }

    @Override
    public List<String> getCourse(String userId) {
        return courseMemberMapper.getCourse(userId);
    }

    @Override
    public int getMemberCount(String cno) {
        return courseMemberMapper.getMemberCount(cno);
    }

}
